package main

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"golang.org/x/sync/errgroup"
	"net/http"
	"os/signal"
	"syscall"
)

func serverApp(ctx context.Context, cancel context.CancelFunc) error {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprintln(w, "hello server")
	})

	go func() {
		err := http.ListenAndServe("0.0.0.0:8080", mux)
		if err != nil {
			fmt.Printf("start server error: %v\n", err)
			cancel()
		}
	}()

	<-ctx.Done()
	fmt.Println("server stop")
	return nil
}

func signalNotify(ctx context.Context) error {
	ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	<-ctx.Done()
	return errors.New("server stop with signal")
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	group, errCtx := errgroup.WithContext(ctx)

	group.Go(func() error {
		return serverApp(errCtx, cancel)
	})
	group.Go(func() error {
		return signalNotify(errCtx)
	})

	// 捕获err
	err := group.Wait()
	if err != nil {
		fmt.Printf("server quit: %v", err)
	}
}
